const app = getApp();
const Logger = require('../../utils/logUtil.js');

const PROCUCT_MAP = {
  'PWashShoes': 'shoe_cleaning',             // 洗鞋
  'PPacakgePickUp': 'pickup',        // 代取快递
  'PWashClothes': 'laundry',         // 洗衣
  'PPrintBlackAndWhite': 'print_bw',  // 黑白打印
  'PPaoTui': 'PPaoTui',    // 跑腿业务统一用小写
  'PSnackPickup': 'PSnackPickup'    // 跑腿业务统一用小写t
}

Page({
  data: {
	//common初始化数据
    productId: '',
    productType: '',
    optionsData: {},
    productInformation: {},
    serviceConfigs: [],
    availableTimeList: [],

	//common用户输入的信息
    address: {
      addressId: '',
      name: '',
      phone: '',
      school: '',
      detail: '',
    },
    selectedTimeInfo: {},
    selectedServiceConfigs: {},
    imgFromCheckout:[],
    pickupInputs: [],
	//commonloading状态
    loading: true,
    modalVisible: false,

    // 时间选择器相关字段
    showTimerPicker: false,
    currentSelectedDateIndex: 1,
    currentSelectedTimeIndex: 1,

    // 地址选择器相关字段
    showAddressSelector: false,
    allAddressList: [],

    // 打印相关字段
    fileList: [],
    curPaperNum: '1',
    curCopyNum: '1',
    printNote: '',

    // 跑腿相关字段
    paoTuiTasks: [],
    paoTuiNote: '',
    paoTuiContactPhone: '',

  },

  onLoad: function (options) {
    const param = JSON.parse(decodeURIComponent(options.param));
    Logger.info('placeAnOrder2.onLoad', JSON.stringify(param));
    
    this.setData({
      optionsData: param,
      productId: param.productId,
      productType: PROCUCT_MAP[param.productId],
      loading: true
    });

    // 根据产品类型初始化
    this.initProductData();
  },

  // 根据产品类型初始化数据
  initProductData() {
    console.log("productType:", this.data.productType)
    switch (this.data.productType) {
      case 'shoe_cleaning':
        this.initShoeCleaning();
        break;
      case 'laundry':
        this.initLaundry();
        break;
      case 'pickup':
        this.initPickup();
        break;
      case 'print_bw':
        this.initPrint();
        break;
      case 'PPaoTui':
        this.initPaoTui();
        break;
      case 'PSnackPickup':
        this.initPaoTui();
        break;
      default:
        console.error('未知的产品类型:', this.data.productType);
    }
  },

  // 洗鞋初始化
  initShoeCleaning() {
    this.xiXieCheckoutInit();
  },

  // 洗衣初始化
  initLaundry() {
    this.xiYiCheckoutInit();
  },

  // 快递代取初始化
  initPickup() {
    this.kuaiDiCheckoutInit();
  },

  // 打印初始化
  initPrint() {
    this.printCheckoutInit();
  },

  printCheckoutInit: function() {
    wx.showLoading({ title: '加载中' });
    
    const openId = wx.getStorageSync('openId');
    let params = {
      productId: this.data.optionsData.productId,
      schoolCode: this.data.optionsData.schoolCode,
      openId: openId,
    };

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: { printCheckoutInitRequest: params },
      success: (res) => {
        console.log("printCheckoutInit.res: ", JSON.stringify(res));
        const deliveryTimes = res.result.data?.deliveryTimes || [];
        let defaultAddress = res.result?.data?.address;
        let defaultAddressVo = null;
        // 转换地址数据结构，只有当地址的schoolCode与首页传来的schoolCode匹配时才填充
        if (defaultAddress && defaultAddress.address_code === this.data.optionsData.schoolCode) {
          defaultAddressVo = {
            addressId: defaultAddress.address_id,
            name: defaultAddress.contact_name,
            phone: defaultAddress.contact_phone,
            school: defaultAddress.address_desc,
            detail: defaultAddress.address_detail,
            schoolCode: defaultAddress.address_code,
          };
        } 

        let serviceConfigs = res.result?.data?.product?.serviceConfigs
        
        
        this.setData({
          productInformation: res.result.data,
          address: defaultAddressVo,
          availableTimeList: deliveryTimes,
          selectedTimeInfo: {
            dayOffset: deliveryTimes[1]?.dayOffset ?? '',
            dateStr: deliveryTimes[1]?.dateStr ?? '',
            timeFrames: deliveryTimes[1]?.timeFrames[0] ?? '',
          },
          serviceConfigs: serviceConfigs,
          selectedServiceConfigs: {
            '0_0': {
              serviceIndex: 0,
              optionIndex: 0,
              selectedService: serviceConfigs[0].options[0],
              quantity: 1
            }
          },
          loading: false
        });
        
        this.printComputePrice();
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [printCheckoutInit] 调用失败', err);
        wx.hideLoading();
      },
    });
  },

  // 打印价格计算
  printComputePrice: function() {
    wx.showLoading({ title: '计算中' });
    
    // 获取选中的服务配置和纸张数量
    const selectedConfigs = Object.values(this.data.selectedServiceConfigs);
    if (selectedConfigs.length === 0) {
      wx.hideLoading();
      return;
    }
    
    let params = {
      productId: this.data.optionsData.productId,
      schoolCode: this.data.optionsData.schoolCode,
      selectedServiceConfigs: this.buildServiceConfigsParams(),
      participantId: this.data.optionsData.participantId,
      paperNum: parseInt(this.data.curPaperNum) || 1, // 纸张数量参数
      copyNum: parseInt(this.data.curCopyNum) || 1, // 份数参数
    };

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: { printComputePriceRequest: params },
      success: (res) => {
        console.log("printComputePrice.res: ", JSON.stringify(res));
        // 更新价格信息
        if (res.result && res.result.data) {
          this.setData({
            'productInformation.price': res.result.data,
          });
        }
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [printComputePrice] 调用失败', err);
        wx.hideLoading();
      },
    });
  },

  // 跑腿初始化
  initPaoTui() {
    // 恢复跑腿相关的本地存储数据
    const savedNote = wx.getStorageSync('paoTuiNote');
    const savedPhone = wx.getStorageSync('paoTuiContactPhone');
    const savedTasks = wx.getStorageSync('paoTuiTasks');
    const savedServiceConfigs = wx.getStorageSync('selectedServiceConfigs');
    
    if (savedNote) {
      this.setData({ paoTuiNote: savedNote });
    }
    if (savedPhone) {
      this.setData({ paoTuiContactPhone: savedPhone });
    } else {
      // 如果本地存储没有手机号，尝试从用户信息中获取
      this.getUserPhoneFromServer();
    }
    if (savedTasks && savedTasks.length > 0) {
      this.setData({ paoTuiTasks: savedTasks });
    }
    if (savedServiceConfigs && Object.keys(savedServiceConfigs).length > 0) {
      this.setData({ selectedServiceConfigs: savedServiceConfigs });
    }
    
    this.paoTuiCheckoutInit();
  },
  paoTuiCheckoutInit: function () {
    wx.showLoading({
      title: '加载中',
    });
    let params = {
      paoTuiCheckOutRequest:{
        productId: this.data.optionsData.productId,
        schoolCode: this.data.optionsData.schoolCode,
      }
    };
    const cloudFunctionName = 'xiaoBangCommonFunction';
    console.log("paoTuiCheckoutInit.paoTuiCheckOutRequest.params: ", JSON.stringify(params));
    wx.cloud.callFunction({
      name: cloudFunctionName,
      data: params,
      success: (res) => {
        // 从 product 模型中获取服务配置
        const serviceConfigs = res.result?.data?.product?.serviceConfigs || [];
        
        // 如果 selectedServiceConfigs 为空且 serviceConfigs 有值，则默认选中第一个服务配置
        let selectedServiceConfigs = this.data.selectedServiceConfigs;
        if (Object.keys(selectedServiceConfigs).length === 0 && serviceConfigs.length > 0) {
          selectedServiceConfigs = {
            '0_0': {
              serviceIndex: 0,
              optionIndex: 0,
              selectedService: serviceConfigs[0].options[0],
              quantity: 1
            }
          };
        }
        
        this.setData({
          productInformation: res.result.data,
          serviceConfigs: serviceConfigs,
          selectedServiceConfigs: selectedServiceConfigs,
        });
        
        // 如果是跑腿服务，需要生成跑腿任务
        if (this.data.productType === 'PPaoTui' && Object.keys(selectedServiceConfigs).length > 0) {
          this.generatePaoTuiTasks();
          this.paoTuiComputePrice();
        }
        
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [checkOut] 调用失败', err);
        wx.hideLoading();
      },
    });
  },
  kuaiDiCheckoutInit: function() {
    wx.showLoading({ title: '加载中' });
    
    const openId = wx.getStorageSync('openId');
    let params = {
      productId: this.data.optionsData.productId,
      schoolCode: this.data.optionsData.schoolCode,
      openId: openId,
    };

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: { kuaiDiCheckoutInitRequest: params },
      success: (res) => {
        console.log("kuaiDiCheckoutInit.res: ", JSON.stringify(res));
        const deliveryTimes = res.result.data?.deliveryTimes || [];
        let defaultAddress = res.result?.data?.address;
        const serviceConfigs = res.result?.data?.product?.serviceConfigs || [];
        
        let defaultAddressVo = null;
        // 快递代取：只有当地址的schoolCode与首页传来的schoolCode匹配时才填充
        if (defaultAddress && defaultAddress.schoolCode === this.data.optionsData.schoolCode) {
          defaultAddressVo = {
            addressId: defaultAddress.addressId,
            name: defaultAddress.name,
            phone: defaultAddress.phone,
            school: defaultAddress.school,
            detail: defaultAddress.detail,
            schoolCode: defaultAddress.schoolCode,
          };
        }
      
        const initialPickupInputs = [{
          stationName: '',
          code: '',
          photos: [],
          isPopupVisible: false,
          tempCode: ''
        }];

        this.setData({
          productInformation: res.result.data,
          address: defaultAddressVo,
          availableTimeList: deliveryTimes,
          selectedTimeInfo: {
            dayOffset: deliveryTimes[1]?.dayOffset ?? '',
            dateStr: deliveryTimes[1]?.dateStr ?? '',
            timeFrames: deliveryTimes[1]?.timeFrames[0] ?? '',
          },
          serviceConfigs: serviceConfigs,
          selectedServiceConfigs: {
            '0_0': {
              serviceIndex: 0,
              optionIndex: 0,
              selectedService: serviceConfigs[0].options[0],
              quantity: 1
            }
          },
          pickupInputs: initialPickupInputs,
          loading: false
        });
        
        this.kuaiDiDaiQuComputePrice();
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [kuaiDiCheckoutInit] 调用失败', err);
        wx.hideLoading();
      },
    });
  },
  kuaiDiDaiQuComputePrice: function () {
    wx.showLoading({ title: '计算中' });
    let params = {
      productId: this.data.optionsData.productId,
      schoolCode: this.data.optionsData.schoolCode,
      selectedServiceConfigs: this.buildServiceConfigsParams(),
      pickupInputs: this.data.pickupInputs,
      participantId: this.data.optionsData.participantId,
    };

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: { kuaiDiDaiQuComputePriceRequest: params },
      success: (res) => {
        console.log("kuaiDiDaiQuComputePrice.res: ", JSON.stringify(res));
        // 更新价格信息
        if (res.result && res.result.data) {
          this.setData({
            'productInformation.price': res.result.data,
          });
        }
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [kuaiDiDaiQuComputePrice] 调用失败', err);
        wx.hideLoading();
      },
    });
  },
  // 洗鞋结算初始化
  xiXieCheckoutInit: function() {
    wx.showLoading({ title: '加载中' });
    
    const openId = wx.getStorageSync('openId');
    let params = {
      productId: this.data.optionsData.productId,
      schoolCode: this.data.optionsData.schoolCode,
      openId: openId,
    };

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: { xiXieCheckoutInitRequest: params },
      success: (res) => {
        console.log("xiXieCheckoutInit.res: ", JSON.stringify(res));
        const deliveryTimes = res.result.data?.deliveryTimes || [];
        let defaultAddress = res.result?.data?.address;
        const serviceConfigs = res.result?.data?.product?.serviceConfigs || [];
        let defaultAddressVo = null;
        // 洗鞋：只有当地址的schoolCode与首页传来的schoolCode匹配时才填充
        if (defaultAddress && defaultAddress.schoolCode === this.data.optionsData.schoolCode) {
          defaultAddressVo = {
            addressId: defaultAddress.addressId,
            name: defaultAddress.name,
            phone: defaultAddress.phone,
            school: defaultAddress.school,
            detail: defaultAddress.detail,
            schoolCode: defaultAddress.schoolCode,
          };
        }
      
        this.setData({
          productInformation: res.result.data,
          address: defaultAddressVo,
          availableTimeList: deliveryTimes,
          selectedTimeInfo: {
            dayOffset: deliveryTimes[1]?.dayOffset ?? '',
            dateStr: deliveryTimes[1]?.dateStr ?? '',
            timeFrames: deliveryTimes[1]?.timeFrames[0] ?? '',
          },
          serviceConfigs: serviceConfigs,
          selectedServiceConfigs: {
            '0_0': {
              serviceIndex: 0,
              optionIndex: 0,
              selectedService: serviceConfigs[0].options[0],
              quantity: 1
            }
          },
          loading: false
        });
        
        this.xiXieComputePrice();
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [xiXieCheckoutInit] 调用失败', err);
        wx.hideLoading();
      },
    });
  },

  // 洗鞋价格计算
  xiXieComputePrice: function() {
    wx.showLoading({ title: '计算中' });
    
    let params = {
      productId: this.data.optionsData.productId,
      schoolCode: this.data.optionsData.schoolCode,
      selectedServiceConfigs: this.buildServiceConfigsParams(),
      participantId: this.data.optionsData.participantId,
    };

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: { xiXieComputePriceRequest: params },
      success: (res) => {
        console.log("xiXieComputePrice.res: ", JSON.stringify(res));
        // 更新价格信息
        if (res.result && res.result.data) {
          this.setData({
            'productInformation.price': res.result.data,
          });
        }
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [xiXiePriceCompute] 调用失败', err);
        wx.hideLoading();
      },
    });
  },

  // 构建服务配置参数
  buildServiceConfigsParams() {
    const selectedConfigs = Object.values(this.data.selectedServiceConfigs).map(config => ({
      selectedService: config.selectedService,
      quantity: config.quantity || 1
    }));
    return selectedConfigs;
  },

  // 洗鞋组件事件处理
  onShoeCleaningServiceConfigChange(e) {
    const { selectedServiceConfigs } = e.detail;
    this.setData({ selectedServiceConfigs }, () => {
      this.xiXieComputePrice();
    });
  },

  onShoeCleaningAddressSelect() {
    this.addressSelection();
  },

  onShoeCleaningTimeSelect() {
    this.onSelectTimeTap();
  },

  onShoeCleaningImgFromCheckoutChange(e) {
    const { imgFromCheckout } = e.detail;
    this.setData({ imgFromCheckout });
  },

  // 洗衣组件事件处理
  onLaundryServiceConfigChange(e) {
    const { selectedServiceConfigs } = e.detail;
    this.setData({ selectedServiceConfigs }, () => {
      if (typeof this.xiYiComputePrice === 'function') {
        this.xiYiComputePrice();
      } else if (typeof this.xiXieComputePrice === 'function') {
        this.xiXieComputePrice();
      }
    });
  },

  onLaundryAddressSelect() {
    this.addressSelection();
  },

  onLaundryTimeSelect() {
    this.onSelectTimeTap();
  },

  onLaundryImgFromCheckoutChange(e) {
    const { imgFromCheckout } = e.detail;
    this.setData({ imgFromCheckout });
  },

  // 兼容：当前未实现独立的洗衣初始化/计价方法，先复用洗鞋逻辑，避免运行时报错
  xiYiCheckoutInit: function() {
      this.xiXieCheckoutInit();
  },

  xiYiComputePrice: function() {
      this.xiXieComputePrice();
  },

  // 快递代取组件事件处理
  onPickupServiceConfigChange(e) {
    const { selectedServiceConfigs } = e.detail;
    this.setData({ selectedServiceConfigs }, () => {
      this.kuaiDiDaiQuComputePrice();
    });
  },

  onPickupAddressSelect() {
    console.log('placeAnOrder2: onPickupAddressSelect 被调用');
    this.addressSelection();
  },

  onPickupTimeSelect() {
    this.onSelectTimeTap();
  },

  onPickupInputsChange(e) {
    const { pickupInputs } = e.detail;
    this.setData({ pickupInputs });
  },

  onPickupPriceRecalculate() {
    // 重新计算价格
    this.kuaiDiDaiQuComputePrice();
  },

  onPickupImgFromCheckoutChange(e) {
    const { imgFromCheckout } = e.detail;
    this.setData({ imgFromCheckout });
  },

  // 打印组件事件处理
  onPrintAddressSelect() {
    this.addressSelection();
  },

  onPrintTimeSelect() {
    this.onSelectTimeTap();
  },

  onPrintServiceConfigChange(e) {
    const { selectedServiceConfigs } = e.detail;
    this.setData({ selectedServiceConfigs }, () => {
      this.printComputePrice();
    });
  },

  onPrintFileListChange(e) {
    const { fileList } = e.detail;
    this.setData({ fileList });
  },

  onPrintPaperNumChange(e) {
    const { curPaperNum } = e.detail;
    this.setData({ curPaperNum });
  },

  onPrintCopyNumChange(e) {
    const { curCopyNum } = e.detail;
    this.setData({ curCopyNum });
  },

  onPrintNoteChange(e) {
    const { printNote } = e.detail;
    this.setData({ printNote });
  },

  onPrintPriceRecalculate() {
    // 重新计算价格
    this.printComputePrice();
  },

  // 跑腿相关事件处理方法
  onPaoTuiServiceConfigChange(e) {
    const { selectedServiceConfigs } = e.detail;
    this.setData({
      selectedServiceConfigs: selectedServiceConfigs
    });
    // 重新生成跑腿任务并计算价格
    this.generatePaoTuiTasks();
    this.paoTuiComputePrice();
  },

  onPaoTuiLogin(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv, cloudID } = e.detail;
      const params = { encryptedData, iv, cloudID};
      console.log("onPaoTuiLogin.getUserInfo.params: ", JSON.stringify(params));
      wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getUserInfoRequest: params
        },
        success: (res) => {
          console.log("onPaoTuiLogin.getUserInfo.res: ", JSON.stringify(res));
          // 保存手机号到 paoTuiContactPhone 字段
          if (res.result.code === 200 && res.result.data.phone) {
            this.setData({
              paoTuiContactPhone: res.result.data.phone
            });
            // 保存到本地存储，避免重复授权
            wx.setStorageSync('paoTuiContactPhone', res.result.data.phone);
            wx.showToast({
              title: '手机号授权成功',
              icon: 'success'
            });
          }
        },
        fail: (err) => {
          console.error('保存用户手机号失败:', err);
          wx.showToast({
            title: '手机号授权失败',
            icon: 'none'
          });
        },
      });
    } else {
      wx.showToast({
        title: '请授权手机号,方便联系您',
        icon: 'none'
      });
    }
  },

  onPaoTuiNoteChange(e) {
    const { paoTuiNote } = e.detail;
    this.setData({
      paoTuiNote: paoTuiNote
    });
    // 实时保存到本地存储，防止意外丢失
    wx.setStorageSync('paoTuiNote', paoTuiNote);
  },

  onPaoTuiDeleteTask(e) {
    const { index } = e.detail;
    const { paoTuiTasks } = this.data;
    
    // 获取要删除的任务信息
    const taskToDelete = paoTuiTasks[index];
    
    // 找到对应的服务配置
    const key = `${taskToDelete.serviceIndex}_${taskToDelete.optionIndex}`;
    const selectedServiceConfigs = { ...this.data.selectedServiceConfigs };
    
    if (selectedServiceConfigs[key]) {
      // 如果数量大于1，减少数量
      if (selectedServiceConfigs[key].quantity > 1) {
        selectedServiceConfigs[key].quantity -= 1;
      } else {
        // 如果数量为1，删除整个配置
        delete selectedServiceConfigs[key];
      }
      
      this.setData({ selectedServiceConfigs });
      // 重新生成跑腿任务
      this.generatePaoTuiTasks();
    }
  },

  async onPaoTuiUploadPhoto(e) {
    const { taskIndex } = e.detail;
    const paoTuiTasks = [...this.data.paoTuiTasks];
    const task = paoTuiTasks[taskIndex];
    
    if (!task.photos) {
      task.photos = [];
    }
    
    if (task.photos.length >= 3) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      });
      return;
    }
    
    try {
      const res = await wx.chooseImage({
        count: 3 - task.photos.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });
      
      wx.showLoading({ title: '上传中...' });
      
      const uploadPromises = res.tempFilePaths.map(async (filePath) => {
        const cloudPath = `paotui-task-photos/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.jpg`;
        const uploadRes = await wx.cloud.uploadFile({
          cloudPath,
          filePath
        });
        return uploadRes.fileID;
      });
      
      const uploadedFileIDs = await Promise.all(uploadPromises);
      task.photos = [...task.photos, ...uploadedFileIDs];
      
      this.setData({ paoTuiTasks });
      wx.hideLoading();
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      });
      
    } catch (error) {
      wx.hideLoading();
      console.error('跑腿任务图片上传失败:', error);
      wx.showToast({
        title: '上传失败',
        icon: 'error'
      });
    }
  },

  onPaoTuiPreviewPhoto(e) {
    const { taskIndex, photoIndex } = e.detail;
    const task = this.data.paoTuiTasks[taskIndex];
    const current = task.photos[photoIndex];
    
    wx.previewImage({
      current,
      urls: task.photos
    });
  },

  onPaoTuiDeletePhoto(e) {
    const { taskIndex, photoIndex } = e.detail;
    const paoTuiTasks = [...this.data.paoTuiTasks];
    const task = paoTuiTasks[taskIndex];
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          task.photos.splice(photoIndex, 1);
          this.setData({ paoTuiTasks });
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  onPaoTuiTaskInputChange(e) {
    const { index, field, value } = e.detail;
    const paoTuiTasks = [...this.data.paoTuiTasks];
    paoTuiTasks[index][field] = value;
    this.setData({
      paoTuiTasks: paoTuiTasks
    });
    // 保存到本地存储
    wx.setStorageSync('paoTuiTasks', paoTuiTasks);
  },

  // 地址选择
  addressSelection: function () {
    console.log('placeAnOrder2: addressSelection 被调用');
    wx.showLoading({ title: '加载中' });

    const openId = wx.getStorageSync('openId');
    const params = { userId: openId };
    console.log('placeAnOrder2: 获取用户地址列表, openId=', openId);
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getUserInfoRequest: params
      },
      success: (res) => {
        console.log('placeAnOrder2: 获取地址列表成功', res.result.data.address);
        const allAddressList = res.result.data.address;
        
        // 显示地址选择弹窗，不过滤地址
        this.setData({
          allAddressList: allAddressList,
          showAddressSelector: true
        }, () => {
          console.log('placeAnOrder2: showAddressSelector 已设置为 true');
          console.log('placeAnOrder2: 当前 showAddressSelector 值:', this.data.showAddressSelector);
        });
        
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [xiaoBangCommonFunction] 调用失败', JSON.stringify(err));
        wx.hideLoading();
      },
    });
  },

  // 地址选择器事件处理
  onAddressSelected(e) {
    const { address } = e.detail;
    
    // 转换地址数据结构，使其与组件期望的格式一致
    this.setData({
      address: {
        addressId: address.addressId,
        name: address.contactName,
        phone: address.contactPhone,
        school: address.addressDesc,
        detail: address.addressDetail,
        schoolCode: address.addressCode,
      },
      showAddressSelector: false
    });
  },

  // 新增地址
  onAddNewAddress() {
    this.setData({
      showAddressSelector: false
    });
    
    // 跳转到新增地址页面，传递 undefined 参数触发自动填充学校信息
    wx.navigateTo({
      url: '/pages/addEditingAddress/index?option=undefined',
    });
  },

  // 关闭地址选择器
  onCloseAddressSelector() {
    this.setData({
      showAddressSelector: false
    });
  },

  // 时间选择
  onSelectTimeTap() {
    this.setData({ showTimerPicker: true });
  },

  // 时间选择器相关方法
  toggleTimePicker() {
    this.setData({
      showTimerPicker: false
    });
  },

  onTimePickerTap() {
    // 阻止事件冒泡，防止点击时间选择器内容时关闭弹窗
    return;
  },

  onSelectDate(e) {
    this.setData({
      currentSelectedDateIndex: e.currentTarget.dataset.index
    });
  },

  onSelectTime(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentSelectedTimeIndex: index,
      selectedTimeInfo: {
        dayOffset: this.data.availableTimeList[this.data.currentSelectedDateIndex].dayOffset,
        dateStr: this.data.availableTimeList[this.data.currentSelectedDateIndex].dateStr,
        timeFrames: this.data.availableTimeList[this.data.currentSelectedDateIndex].timeFrames[index]
      },
      showTimerPicker: false
    });
    // 显示选择成功提示
    wx.showToast({
      title: '时间选择成功',
      icon: 'success',
      duration: 1000
    });
  },
  xiXiePayNow: async function () {
    try {
      // 校验服务配置选择
      if (this.data.serviceConfigs && this.data.serviceConfigs.length > 0) {
        const selectedConfigs = Object.values(this.data.selectedServiceConfigs);
        if (selectedConfigs.length === 0) {
          wx.showToast({
            title: '请选择服务配置',
            icon: 'error',
          });
          Logger.warn('payNow-未选择服务配置', JSON.stringify(this.data.selectedServiceConfigs));
          return;
        }
      }

      // 校验地址选择
      if (!this.data.address || !this.data.address.school) {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'error',
        });
        Logger.warn('payNow-未选择地址', JSON.stringify(this.data.address));
        return;
      }

      // 校验时间选择
      if (!this.data.selectedTimeInfo || !this.data.selectedTimeInfo.timeFrames) {
        wx.showToast({
          title: '请选择配送时间',
          icon: 'error',
        });
        Logger.warn('payNow-未选择时间', JSON.stringify(this.data.selectedTimeInfo));
        return;
      }

      // 校验图片上传（如果需要）
      if (this.data.productInformation.uploadImgRequiredSwitch && (!this.data.imgFromCheckout || this.data.imgFromCheckout.length === 0)) {
        wx.showToast({
          title: '请上传相关图片',
          icon: 'error',
        });
        Logger.warn('payNow-未上传图片', JSON.stringify(this.data.imgFromCheckout));
        return;
      }

      // 构建订单参数
      const orderParams = {
        productId: this.data.optionsData.productId,
        participantId: this.data.optionsData.participantId,
        schoolCode: this.data.optionsData.schoolCode,
        address: this.data.address,
        selectedTimeInfo: this.data.selectedTimeInfo,
        serviceConfigs: this.buildServiceConfigsParams(),
        imgFromCheckout: this.data.imgFromCheckout || [],
        price: this.data.productInformation.price,
      };
      console.log("payNow-创建订单参数", JSON.stringify(orderParams));
      
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          xiXieCreateOrderRequest: orderParams
        }
      });
      
      console.log("payNow.createOrder.res: ", JSON.stringify(res));
      wx.hideLoading();
      
      if (res.result.code === 500) {
        wx.showToast({
          title: res.result.message,
          icon: 'error',
          duration: 2000,
        });
        return;
      }

      // 处理支付
      if (orderParams.price.payAmount > 0) {
        try {
          const orderId = await this.handlePayment(res.result.data);
          await this.handlePaySuccess(orderId);
        } catch (payErr) {
          //todo yg p0.c 改为Logger
          console.error('支付流程异常', payErr);
        }
      } else {
        await this.handlePaySuccess(res.result.data.orderId);
      }
    } catch (err) {
      console.error('创建订单调用失败', JSON.stringify(err.stack || err));
      wx.hideLoading();
    }
  },

  // 洗衣支付
  xiYiPayNow: async function () {
    await this.xiXiePayNow();
  },

  // 快递代取支付
  kuaiDiDaiQuPayNow: async function () {
    try {
      // 校验服务配置选择
      if (this.data.serviceConfigs && this.data.serviceConfigs.length > 0) {
        const selectedConfigs = Object.values(this.data.selectedServiceConfigs);
        if (selectedConfigs.length === 0) {
          wx.showToast({
            title: '请选择服务配置',
            icon: 'error',
          });
          Logger.warn('payNow-未选择服务配置', JSON.stringify(this.data.selectedServiceConfigs));
          return;
        }
      }

      // 校验每个包裹的取件码或图片至少有一个
      const pickupInputs = this.data.pickupInputs || [];
      const invalidPickup = pickupInputs.some(item => {
        const codeEmpty = !item.code || item.code.trim() === '';
        const photosEmpty = !item.photos || item.photos.length === 0;
        return codeEmpty && photosEmpty;
      });
      if (invalidPickup) {
        wx.showToast({
          title: '请填写所有包裹的取件码或上传至少一张包裹图片',
          icon: 'none',
        });
        return;
      }

      // 构建订单参数
      const orderParams = {
        productId: this.data.optionsData.productId,
        participantId: this.data.optionsData.participantId,
        schoolCode: this.data.optionsData.schoolCode,
        address: this.data.address,
        selectedTimeInfo: this.data.selectedTimeInfo,
        serviceConfigs: this.buildServiceConfigsParams(),
        imgFromCheckout: this.data.imgFromCheckout || [],
        price: this.data.productInformation.price,
        pickupInputs: this.data.pickupInputs,
      };
      console.log("payNow-创建订单参数", JSON.stringify(orderParams));
      
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          kuaiDiCreateOrderRequest: orderParams
        }
      });
      
      console.log("payNow.createOrder.res: ", JSON.stringify(res));
      wx.hideLoading();
      
      if (res.result.code === 500) {
        wx.showToast({
          title: res.result.message,
          icon: 'error',
          duration: 2000,
        });
        return;
      }

      // 处理支付
      if (orderParams.price.payAmount > 0) {
        try {
          const orderId = await this.handlePayment(res.result.data);
          await this.handlePaySuccess(orderId);
        } catch (payErr) {
          console.error('支付流程异常', payErr);
        }
      } else {
        await this.handlePaySuccess(res.result.data.orderId);
      }
    } catch (err) {
      console.error('创建订单调用失败', JSON.stringify(err.stack || err));
      wx.hideLoading();
    }
  },

  // 打印支付
  printPayNow: async function () {
    try {
      // 校验服务配置选择
      if (this.data.serviceConfigs && this.data.serviceConfigs.length > 0) {
        const selectedConfigs = Object.values(this.data.selectedServiceConfigs);
        if (selectedConfigs.length === 0) {
          wx.showToast({
            title: '请选择服务配置',
            icon: 'error',
          });
          Logger.warn('payNow-未选择服务配置', JSON.stringify(this.data.selectedServiceConfigs));
          return;
        }
      }

      // 校验文件上传
      if (!this.data.fileList || this.data.fileList.length === 0) {
        wx.showToast({
          title: '请上传打印文件',
          icon: 'error',
        });
        Logger.warn('payNow-未上传文件', JSON.stringify(this.data.fileList));
        return;
      }

      // 校验地址选择
      if (!this.data.address || !this.data.address.school) {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'error',
        });
        Logger.warn('payNow-未选择地址', JSON.stringify(this.data.address));
        return;
      }

      // 校验时间选择
      if (!this.data.selectedTimeInfo || !this.data.selectedTimeInfo.timeFrames) {
        wx.showToast({
          title: '请选择配送时间',
          icon: 'error',
        });
        Logger.warn('payNow-未选择时间', JSON.stringify(this.data.selectedTimeInfo));
        return;
      }

      // 构建订单参数
      const orderParams = {
        productId: this.data.optionsData.productId,
        participantId: this.data.optionsData.participantId,
        schoolCode: this.data.optionsData.schoolCode,
        address: this.data.address,
        selectedTimeInfo: this.data.selectedTimeInfo,
        serviceConfigs: this.buildServiceConfigsParams(),
        imgFromCheckout: this.data.imgFromCheckout || [],
        price: this.data.productInformation.price,
        fileList: this.data.fileList || [],
        curPaperNum: this.data.curPaperNum,
        curCopyNum: this.data.curCopyNum,
        printNote: this.data.printNote,
      };
      console.log("payNow-创建订单参数", JSON.stringify(orderParams));
      
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          printCreateOrderRequest: orderParams
        }
      });
      
      console.log("payNow.createOrder.res: ", JSON.stringify(res));
      wx.hideLoading();
      
      if (res.result.code === 500) {
        wx.showToast({
          title: res.result.message,
          icon: 'error',
          duration: 2000,
        });
        return;
      }

      // 处理支付
      if (orderParams.price.payAmount > 0) {
        try {
          const orderId = await this.handlePayment(res.result.data);
          await this.handlePaySuccess(orderId);
        } catch (payErr) {
          console.error('支付流程异常', payErr);
        }
      } else {
        await this.handlePaySuccess(res.result.data.orderId);
      }
    } catch (err) {
      console.error('创建订单调用失败', JSON.stringify(err.stack || err));
      wx.hideLoading();
    }
  },

  // 跑腿支付
  paoTuiPayNow: async function () {
    Logger.info('paoTuiPayNow-开始支付流程', JSON.stringify(this.data));
    if (!this.payPaoTuiOrderValidate()) {
      return;
    }
    //创建跑腿订单
    this.paoTuiCreateOrderRequest();
  },

  // 跑腿业务表单校验方法
  payPaoTuiOrderValidate() {
    // 验证手机号是否已授权
    if (!this.data.paoTuiContactPhone || this.data.paoTuiContactPhone.trim() === '') {
      wx.showToast({
        title: '请先授权手机号',
        icon: 'error',
      });
      Logger.warn('payPaoTuiOrder-未授权手机号');
      return false;
    }
    // 验证是否有选择跑腿任务
    if (this.data.paoTuiTasks.length === 0) {
      wx.showToast({
        title: '请选择跑腿服务',
        icon: 'error',
      });
      Logger.warn('payPaoTuiOrder-未选择跑腿服务');
      return false;
    }
    // 验证每个跑腿任务的配置
    for (let i = 0; i < this.data.paoTuiTasks.length; i++) {
      const task = this.data.paoTuiTasks[i];
      // 验证快递代寄地址（有红色星号的必填字段）
      if (task.serviceIndex === 0 && task.optionIndex === 0) {
        if (!task.pickupAddressText || !task.pickupTimeText || !task.deliveryAddressText) {
          wx.showToast({
            title: '请填写完整的快递代寄信息',
            icon: 'none'
          });
          return false;
        }
      }
      // 验证食堂取餐地址（有红色星号的必填字段）
      else if (task.serviceIndex === 0 && task.optionIndex === 1) {
        if (!task.pickupAddressText || !task.deliveryAddressText) {
          wx.showToast({
            title: '请填写完整的食堂取餐信息',
            icon: 'none'
          });
          return false;
        }
      }
      // 验证代取外卖地址（有红色星号的必填字段）
      else if (task.serviceIndex === 0 && task.optionIndex === 2) {
        if (!task.pickupAddressText || !task.deliveryAddressText) {
          wx.showToast({
            title: '请填写完整的代取外卖信息',
            icon: 'none'
          });
          return false;
        }
      }
      // 其他跑腿：不需要地址和时间验证，只需要图片（可选）
    }
    // 校验服务配置选择
    if (this.data.serviceConfigs && this.data.serviceConfigs.length > 0) {
      const selectedConfigs = Object.values(this.data.selectedServiceConfigs);
      if (selectedConfigs.length === 0) {
        wx.showToast({
          title: '请选择服务配置',
          icon: 'error',
        });
        Logger.warn('payPaoTuiOrder-未选择服务配置', JSON.stringify(this.data.selectedServiceConfigs));
        return false;
      }
    }
    return true;
  },

  paoTuiCreateOrderRequest() {
    wx.showLoading({
      title: '加载中',
    });
    let params = {
      paoTuiCreateOrderRequest:{
        productId: this.data.productInformation.product.productId,
        schoolCode: this.data.optionsData.schoolCode,
        paoTuiTasks: this.data.paoTuiTasks,
        paoTuiNote: this.data.paoTuiNote,
        selectedServiceConfigs: this.data.selectedServiceConfigs,
        paoTuiContactPhone: this.data.paoTuiContactPhone,
        payAmount: this.data.productInformation.price.payAmount
      }
    };
    const cloudFunctionName = 'xiaoBangCommonFunction';
    console.log("paoTuiCreateOrderRequest.paoTuiPriceCreateOrderRequest.params: ", JSON.stringify(params));
    wx.cloud.callFunction({
      name: cloudFunctionName,
      data: params,
      success: (res) => {
        console.log("paoTui create order res: ", JSON.stringify(res))
        if (this.data.productInformation.price.payAmount > 0) {
          this.handlePayment(res.result.data)
            .then(orderId => this.handlePaySuccess(orderId))
            .catch(payErr => {
              Logger.error('payNow-支付流程异常', payErr);
            })
            .finally(() => {
              wx.hideLoading();
            });
        } else {
          this.handlePaySuccess(res.result.data.orderId)
            .finally(() => {
              wx.hideLoading();
            });
        }
      },
      fail: (err) => {
        console.error('[云函数] [checkOut] 调用失败', err);
        wx.hideLoading();
      },
    });
  },

  // 跑腿相关核心方法
  generatePaoTuiTasks() {
    const selectedConfigs = Object.values(this.data.selectedServiceConfigs);
    const paoTuiTasks = [];
    const existingTasks = this.data.paoTuiTasks || [];
    
    selectedConfigs.forEach(config => {
      const quantity = config.quantity || 1;
      
      for (let i = 0; i < quantity; i++) {
        // 查找是否已存在相同配置的任务
        const existingTaskIndex = existingTasks.findIndex(task => 
          task.serviceIndex === config.serviceIndex && 
          task.optionIndex === config.optionIndex
        );
        
        let task;
        if (existingTaskIndex >= 0) {
          // 如果存在相同配置的任务，保留其配置信息
          task = { ...existingTasks[existingTaskIndex] };
          // 移除已使用的任务，避免重复
          existingTasks.splice(existingTaskIndex, 1);
        } else {
          // 创建新任务
          task = {
            serviceIndex: config.serviceIndex,
            optionIndex: config.optionIndex,
            serviceName: config.selectedService.name,
            price: config.selectedService.price,
            photos: [],
            pickupAddressText: '',
            pickupTimeText: '',
            deliveryAddressText: ''
          };
          
          // 为快递代寄任务添加文本输入字段
          if (config.serviceIndex === 0 && config.optionIndex === 0) {
            task.pickupAddressText = '';
            task.pickupTimeText = '';
            task.deliveryAddressText = '';
          }
          // 为食堂取餐任务添加文本输入字段
          else if (config.serviceIndex === 0 && config.optionIndex === 1) {
            task.pickupAddressText = '';
            task.deliveryAddressText = '';
          }
          // 为代取外卖任务添加文本输入字段
          else if (config.serviceIndex === 0 && config.optionIndex === 2) {
            task.pickupAddressText = '';
            task.deliveryAddressText = '';
          }
        }
        
        paoTuiTasks.push(task);
      }
    });
    
    this.setData({ paoTuiTasks });
  },

  paoTuiComputePrice() {
    wx.showLoading({
      title: '加载中',
    });
    let params = {
      paoTuiPriceComputeRequest:{
        selectedServiceConfigs: this.data.selectedServiceConfigs,
        schoolCode: this.data.optionsData.schoolCode,
      }
    };
    const cloudFunctionName = 'xiaoBangCommonFunction';
    console.log("paoTuiComputePrice.paoTuiPriceComputeRequest.params: ", JSON.stringify(params));
    wx.cloud.callFunction({
      name: cloudFunctionName,
      data: params,
      success: (res) => {
        this.data.productInformation.price.totalAmount = res.result.data.totalAmount;
        this.data.productInformation.price.payAmount = res.result.data.payAmount;
        this.setData({
          productInformation: this.data.productInformation,
        });
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('[云函数] [checkOut] 调用失败', err);
        wx.hideLoading();
      },
    });
  },

  // 从服务器获取用户手机号
  getUserPhoneFromServer() {
    const openId = wx.getStorageSync('openId');
    if (!openId) {
      return;
    }
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getUserInfoRequest: { userId: openId }
      },
      success: (res) => {
        console.log("getUserPhoneFromServer.getUserInfo.res: ", JSON.stringify(res));
        if (res.result.code === 200 && res.result.data.phone) {
          this.setData({
            paoTuiContactPhone: res.result.data.phone
          });
          // 保存到本地存储
          wx.setStorageSync('paoTuiContactPhone', res.result.data.phone);
        }
      },
      fail: (err) => {
        console.error('获取用户手机号失败:', err);
      }
    });
  },

  // 支付
  payNow: async function () {
    try {
      wx.showLoading({ title: '创建订单中' });
      switch (this.data.productType) {
        case 'shoe_cleaning':
          await this.xiXiePayNow();
          break;
        case 'laundry':
          await this.xiYiPayNow();
          break;
        case 'pickup':
          await this.kuaiDiDaiQuPayNow();
          break;
        case 'print_bw':
          await this.printPayNow();
          break;
        case 'PPaoTui':
          await this.paoTuiPayNow();
          break;
        default:
          console.error('未知的产品类型:', this.data.productType);
      }
    } catch (err) {
      console.error('创建订单调用失败', JSON.stringify(err.stack || err));
      wx.hideLoading();
    }
  },

  // 处理支付
  async handlePayment(paymentData) {
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        timeStamp: paymentData.timeStamp,
        nonceStr: paymentData.nonceStr,
        package: paymentData.package,
        signType: paymentData.signType,
        paySign: paymentData.paySign,
        success: (res) => {
          console.log('支付成功', res);
          resolve(paymentData.orderId);
        },
        fail: (err) => {
          console.error('支付失败', err);
          reject(err);
        }
      });
    });
  },

  // 支付成功后处理
  async handlePaySuccess(orderId) {
    try {
      let params;
      if (this.data.productInformation.product.productId === 'PPaoTui') {
        params = { 
          paoTuiPaySuccessCallbackRequest: {orderId: orderId}
        };
      } else {
        params = { 
          paySuccessCallbackRequest: {orderId: orderId}
        };
        console.log("handlePaySuccess.paySuccessCallback.params: ", JSON.stringify(params));
      }
      
      const paySuccessCallBackRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: params
      });
      
      console.log("handlePaySuccess.paySuccessCallback.res: ", JSON.stringify(paySuccessCallBackRes));
      
      // 清除本地存储的所有表单信息
      wx.removeStorageSync('paoTuiNote');
      wx.removeStorageSync('paoTuiContactPhone');
      wx.removeStorageSync('paoTuiTasks');
      wx.removeStorageSync('selectedServiceConfigs');
      wx.removeStorageSync('pickupInputs');
      wx.removeStorageSync('printNote');
      wx.removeStorageSync('curPaperNum');
      wx.removeStorageSync('printingMode');
      
      wx.switchTab({
        url: '/pages/orderList1/index',
      });
    } catch (err) {
      console.error('支付成功回调失败', err);
    }
  },

  // 显示优惠信息
  showModal: function () {
    if (this.data.productInformation.price.discountList && this.data.productInformation.price.discountList.length > 0) {
      this.setData({
        modalVisible: true,
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '暂无优惠信息',
      });
    }
  },

  // 关闭优惠信息弹窗
  modalVisible: function () {
    this.setData({
      modalVisible: false,
    });
  }
});
